package io.openkunlun.javadsl.client;

import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import io.openkunlun.javadsl.serialization.DaprObject;
import io.openkunlun.javadsl.serialization.DaprSerializer;
import io.openkunlun.javadsl.v1.DaprCommonProtos;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public final class InvokeServiceAction<T> implements DaprAction<InvokeServiceResult<T>> {

    private String id;
    private String method;
    private String contentType;
    private Object data;
    private String serverHost;
    private Integer serverPort;
    private DaprObject<T> daprObject;
    private DaprSerializer daprSerializer;

    /**
     * @param daprClient
     * @return
     */
    @Override
    public InvokeServiceResult<T> invoke(DaprClient daprClient) throws Exception {
        DaprCommonProtos.InvokeRequest request = DaprCommonProtos.InvokeRequest
                .newBuilder()
                .setContentType(contentType)
                .setMethod(method)
                .setData(Any.newBuilder().setValue(ByteString.copyFrom(daprSerializer.serialize(data))))
                .build();

        String app = id;
        if (serverHost != null && serverPort != null) {
            app = id + "@" + serverHost + ":" + serverPort;
        }
        DaprCommonProtos.InvokeService service = DaprCommonProtos.InvokeService.newBuilder().setId(app).setMessage(request).build();
        DaprCommonProtos.InvokeResponse response = daprClient.invokeService(service);
        if (!response.hasData()) {
            return new InvokeServiceResult<>(null, response.getContentType());
        }

        byte[] data = response.getData().getValue().toByteArray();
        return new InvokeServiceResult<>(daprSerializer.deserialize(data, daprObject), response.getContentType());
    }

}
